package com.zanbo.clock.controller;

import com.zanbo.clock.exception.ServiceException;
import com.zanbo.clock.model.base.bean.ResponseBean;
import com.zanbo.clock.model.code.ErrorCode;
import com.zanbo.clock.service.StaffService;
import org.apache.ibatis.annotations.Param;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.time.ZoneOffset;

/**
 * @author: zanbo
 * @description: excel到处控制类
 * @date: 上午 11:00 2021-4-26
 */
@RestController
public class OutInfoController {
    
    @Autowired
    private StaffService staffService;
    
    /**
     * @author: zanbo
     * @description: excel导出方法，传入参数为年份和月份，并返回当月所有员工的签到情况
     * @date: 上午 11:01 2021-4-26
     * @params [year, month, response]
     * @return com.zanbo.clock.model.base.bean.ResponseBean
     */
    @GetMapping("outexcel")
    public ResponseBean OutExcel(@Param("year") String year, @Param("month") String month, HttpServletResponse response) throws IOException {
        if (year == null || month == null) {
            throw new ServiceException(ErrorCode.NONULL);
        }
        LocalDateTime localDateTime = LocalDateTime.of(Integer.parseInt(year),Integer.parseInt(month),1,0,0,0);
        XSSFWorkbook sheets = staffService.outExecl(localDateTime);
        response.setContentType("application/msexcel");
        response.setHeader("content-Disposition", "attachment;filename=" + URLEncoder.encode(year+"年"+month+"月员工签到表.xlsx", "utf-8"));
        response.setHeader("Access-Control-Expose-Headers", "content-Disposition");
        ServletOutputStream outputStream = null;
        try {
            outputStream = response.getOutputStream();
            sheets.write(outputStream);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (outputStream != null) {
                try {
                    outputStream.flush();
                    outputStream.close();
                } catch (IOException e) {
                
                }
            }
        }
        return ResponseBean.success();
    }
    
}
